﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.IO;
using System.Web;
using System.Collections;
using System.Web.UI;
using System.Net.Mail;

namespace Com.CMS263.Util
{

    public static class StringUtil
    {
        /// <summary>
        /// 判断是否由英文字母组成
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsCharEngLish(string str)
        {
            System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z]+$");
            return reg1.IsMatch(str);
        }


        #region 汉字全拼
        private static int[] pyValue = new int[]
                {
                -20319,-20317,-20304,-20295,-20292,-20283,-20265,-20257,-20242,-20230,-20051,-20036,
                -20032,-20026,-20002,-19990,-19986,-19982,-19976,-19805,-19784,-19775,-19774,-19763,
                -19756,-19751,-19746,-19741,-19739,-19728,-19725,-19715,-19540,-19531,-19525,-19515,
                -19500,-19484,-19479,-19467,-19289,-19288,-19281,-19275,-19270,-19263,-19261,-19249,
                -19243,-19242,-19238,-19235,-19227,-19224,-19218,-19212,-19038,-19023,-19018,-19006,
                -19003,-18996,-18977,-18961,-18952,-18783,-18774,-18773,-18763,-18756,-18741,-18735,
                -18731,-18722,-18710,-18697,-18696,-18526,-18518,-18501,-18490,-18478,-18463,-18448,
                -18447,-18446,-18239,-18237,-18231,-18220,-18211,-18201,-18184,-18183, -18181,-18012,
                -17997,-17988,-17970,-17964,-17961,-17950,-17947,-17931,-17928,-17922,-17759,-17752,
                -17733,-17730,-17721,-17703,-17701,-17697,-17692,-17683,-17676,-17496,-17487,-17482,
                -17468,-17454,-17433,-17427,-17417,-17202,-17185,-16983,-16970,-16942,-16915,-16733,
                -16708,-16706,-16689,-16664,-16657,-16647,-16474,-16470,-16465,-16459,-16452,-16448,
                -16433,-16429,-16427,-16423,-16419,-16412,-16407,-16403,-16401,-16393,-16220,-16216,
                -16212,-16205,-16202,-16187,-16180,-16171,-16169,-16158,-16155,-15959,-15958,-15944,
                -15933,-15920,-15915,-15903,-15889,-15878,-15707,-15701,-15681,-15667,-15661,-15659,
                -15652,-15640,-15631,-15625,-15454,-15448,-15436,-15435,-15419,-15416,-15408,-15394,
                -15385,-15377,-15375,-15369,-15363,-15362,-15183,-15180,-15165,-15158,-15153,-15150,
                -15149,-15144,-15143,-15141,-15140,-15139,-15128,-15121,-15119,-15117,-15110,-15109,
                -14941,-14937,-14933,-14930,-14929,-14928,-14926,-14922,-14921,-14914,-14908,-14902,
                -14894,-14889,-14882,-14873,-14871,-14857,-14678,-14674,-14670,-14668,-14663,-14654,
                -14645,-14630,-14594,-14429,-14407,-14399,-14384,-14379,-14368,-14355,-14353,-14345,
                -14170,-14159,-14151,-14149,-14145,-14140,-14137,-14135,-14125,-14123,-14122,-14112,
                -14109,-14099,-14097,-14094,-14092,-14090,-14087,-14083,-13917,-13914,-13910,-13907,
                -13906,-13905,-13896,-13894,-13878,-13870,-13859,-13847,-13831,-13658,-13611,-13601,
                -13406,-13404,-13400,-13398,-13395,-13391,-13387,-13383,-13367,-13359,-13356,-13343,
                -13340,-13329,-13326,-13318,-13147,-13138,-13120,-13107,-13096,-13095,-13091,-13076,
                -13068,-13063,-13060,-12888,-12875,-12871,-12860,-12858,-12852,-12849,-12838,-12831,
                -12829,-12812,-12802,-12607,-12597,-12594,-12585,-12556,-12359,-12346,-12320,-12300,
                -12120,-12099,-12089,-12074,-12067,-12058,-12039,-11867,-11861,-11847,-11831,-11798,
                -11781,-11604,-11589,-11536,-11358,-11340,-11339,-11324,-11303,-11097,-11077,-11067,
                -11055,-11052,-11045,-11041,-11038,-11024,-11020,-11019,-11018,-11014,-10838,-10832,
                -10815,-10800,-10790,-10780,-10764,-10587,-10544,-10533,-10519,-10331,-10329,-10328,
                -10322,-10315,-10309,-10307,-10296,-10281,-10274,-10270,-10262,-10260,-10256,-10254
                };

        private static string[] pyName = new string[]
                {
                "A","Ai","An","Ang","Ao","Ba","Bai","Ban","Bang","Bao","Bei","Ben",
                "Beng","Bi","Bian","Biao","Bie","Bin","Bing","Bo","Bu","Ba","Cai","Can",
                "Cang","Cao","Ce","Ceng","Cha","Chai","Chan","Chang","Chao","Che","Chen","Cheng",
                "Chi","Chong","Chou","Chu","Chuai","Chuan","Chuang","Chui","Chun","Chuo","Ci","Cong",
                "Cou","Cu","Cuan","Cui","Cun","Cuo","Da","Dai","Dan","Dang","Dao","De",
                "Deng","Di","Dian","Diao","Die","Ding","Diu","Dong","Dou","Du","Duan","Dui",
                "Dun","Duo","E","En","Er","Fa","Fan","Fang","Fei","Fen","Feng","Fo",
                "Fou","Fu","Ga","Gai","Gan","Gang","Gao","Ge","Gei","Gen","Geng","Gong",
                "Gou","Gu","Gua","Guai","Guan","Guang","Gui","Gun","Guo","Ha","Hai","Han",
                "Hang","Hao","He","Hei","Hen","Heng","Hong","Hou","Hu","Hua","Huai","Huan",
                "Huang","Hui","Hun","Huo","Ji","Jia","Jian","Jiang","Jiao","Jie","Jin","Jing",
                "Jiong","Jiu","Ju","Juan","Jue","Jun","Ka","Kai","Kan","Kang","Kao","Ke",
                "Ken","Keng","Kong","Kou","Ku","Kua","Kuai","Kuan","Kuang","Kui","Kun","Kuo",
                "La","Lai","Lan","Lang","Lao","Le","Lei","Leng","Li","Lia","Lian","Liang",
                "Liao","Lie","Lin","Ling","Liu","Long","Lou","Lu","Lv","Luan","Lue","Lun",
                "Luo","Ma","Mai","Man","Mang","Mao","Me","Mei","Men","Meng","Mi","Mian",
                "Miao","Mie","Min","Ming","Miu","Mo","Mou","Mu","Na","Nai","Nan","Nang",
                "Nao","Ne","Nei","Nen","Neng","Ni","Nian","Niang","Niao","Nie","Nin","Ning",
                "Niu","Nong","Nu","Nv","Nuan","Nue","Nuo","O","Ou","Pa","Pai","Pan",
                "Pang","Pao","Pei","Pen","Peng","Pi","Pian","Piao","Pie","Pin","Ping","Po",
                "Pu","Qi","Qia","Qian","Qiang","Qiao","Qie","Qin","Qing","Qiong","Qiu","Qu",
                "Quan","Que","Qun","Ran","Rang","Rao","Re","Ren","Reng","Ri","Rong","Rou",
                "Ru","Ruan","Rui","Run","Ruo","Sa","Sai","San","Sang","Sao","Se","Sen",
                "Seng","Sha","Shai","Shan","Shang","Shao","She","Shen","Sheng","Shi","Shou","Shu",
                "Shua","Shuai","Shuan","Shuang","Shui","Shun","Shuo","Si","Song","Sou","Su","Suan",
                "Sui","Sun","Suo","Ta","Tai","Tan","Tang","Tao","Te","Teng","Ti","Tian",
                "Tiao","Tie","Ting","Tong","Tou","Tu","Tuan","Tui","Tun","Tuo","Wa","Wai",
                "Wan","Wang","Wei","Wen","Weng","Wo","Wu","Xi","Xia","Xian","Xiang","Xiao",
                "Xie","Xin","Xing","Xiong","Xiu","Xu","Xuan","Xue","Xun","Ya","Yan","Yang",
                "Yao","Ye","Yi","Yin","Ying","Yo","Yong","You","Yu","Yuan","Yue","Yun",
                "Za", "Zai","Zan","Zang","Zao","Ze","Zei","Zen","Zeng","Zha","Zhai","Zhan",
                "Zhang","Zhao","Zhe","Zhen","Zheng","Zhi","Zhong","Zhou","Zhu","Zhua","Zhuai","Zhuan",
                "Zhuang","Zhui","Zhun","Zhuo","Zi","Zong","Zou","Zu","Zuan","Zui","Zun","Zuo"
                };

        /// <summary>
        /// 把汉字转换成拼音(全拼)
        /// </summary>
        /// <param name="hzString">汉字字符串</param>
        /// <returns>转换后的拼音(全拼)字符串</returns>
        public static string getAllSpells(string hzString)
        {
            // 匹配中文字符
            Regex regex = new Regex("^[\u4e00-\u9fa5]$");
            byte[] array = new byte[2];
            string pyString = "";
            int chrAsc = 0;
            int i1 = 0;
            int i2 = 0;
            char[] noWChar = hzString.ToCharArray();

            for (int j = 0; j < noWChar.Length; j++)
            {
                // 中文字符
                if (regex.IsMatch(noWChar[j].ToString()))
                {
                    array = System.Text.Encoding.Default.GetBytes(noWChar[j].ToString());
                    i1 = (short)(array[0]);
                    i2 = (short)(array[1]);
                    chrAsc = i1 * 256 + i2 - 65536;
                    if (chrAsc > 0 && chrAsc < 160)
                    {
                        pyString += noWChar[j];
                    }
                    else
                    {
                        // 修正部分文字
                        if (chrAsc == -9254)  // 修正“圳”字
                            pyString += "Zhen";
                        else
                        {
                            for (int i = (pyValue.Length - 1); i >= 0; i--)
                            {
                                if (pyValue[i] <= chrAsc)
                                {
                                    pyString += pyName[i];
                                    break;
                                }
                            }
                        }
                    }
                }
                // 非中文字符
                else
                {
                    pyString += noWChar[j].ToString();
                }
            }
            return pyString;
        }
        #endregion

        #region 汉字首拼
        /// <summary>
        /// 获取汉字第一个拼音（北京    BJ）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string getSpells(string input)
        {
            int len = input.Length;
            string reVal = "";
            for (int i = 0; i < len; i++)
            {
                reVal += getSpell(input.Substring(i, 1));
            }
            return reVal;
        }

        private static string getSpell(string cn)
        {
            byte[] arrCN = Encoding.Default.GetBytes(cn);
            if (arrCN.Length > 1)
            {
                int area = (short)arrCN[0];
                int pos = (short)arrCN[1];
                int code = (area << 8) + pos;
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25) max = areacode[i + 1];
                    if (areacode[i] <= code && code < max)
                    {
                        return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    }
                }

                return cn;
            }
            else
            {
                return cn;
            }
        }
        #endregion

        public static string appendParam(String returnStr, String paramId, String paramValue)
        {
            if (returnStr != "")
            {
                if (paramValue != "")
                {
                    returnStr += "&" + paramId + "=" + paramValue;
                }
            }
            else
            {
                if (paramValue != "")
                {
                    returnStr = paramId + "=" + paramValue;
                }
            }

            return returnStr;
        }
        /// <summary>
        /// 是否为双字节字符。
        /// </summary>
        public static bool isDouble(string chr)
        {
            string str = chr.ToString();
            // 使用中文支持编码
            Encoding ecode = Encoding.GetEncoding("gb18030");
            if (ecode.GetByteCount(str) == 2)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 截取字符串长度。
        /// </summary>

        public static string GetText(string stringToSub, int length)
        {
            if (string.IsNullOrEmpty(stringToSub))
            {
                return string.Empty;
            }
            stringToSub = stringToSub.Trim();
            stringToSub = Regex.Replace(stringToSub, "[\\s]{2,}", " ");	//two or more spaces
            stringToSub = Regex.Replace(stringToSub, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");	//<br>
            stringToSub = Regex.Replace(stringToSub, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");	//&nbsp;
            stringToSub = Regex.Replace(stringToSub, "<(.|\\n)*?>", string.Empty);	//any other tags
            stringToSub = stringToSub.Replace("'", "''");

            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            bool isCut = false;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }
                if (nLength > length)
                {
                    isCut = true;
                    break;
                }
            }
            if (isCut)
                return sb.ToString() + "..";
            else
                return sb.ToString();
        }
        public static string CleanHtml(string stringToSub)
        {
            if (string.IsNullOrEmpty(stringToSub))
            {
                return string.Empty;
            }
            stringToSub = stringToSub.Trim();
            stringToSub = Regex.Replace(stringToSub, "[\\s]{2,}", " ");	//two or more spaces
            stringToSub = Regex.Replace(stringToSub, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");	//<br>
            stringToSub = Regex.Replace(stringToSub, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");	//&nbsp;
            stringToSub = Regex.Replace(stringToSub, "<(.|\\n)*?>", string.Empty);	//any other tags
            stringToSub = stringToSub.Replace("'", "''");

            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            bool isCut = false;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

            }

            return sb.ToString();
        }
        /// <summary>
        /// 添加标红和加粗
        /// </summary>
        /// <param name="old"></param>
        /// <param name="cutstr"></param>
        /// <returns></returns>
        public static string GetHtml(string old, int length)
        {
            string newstr = GetText(old, length);
            if (old.IndexOf("</span>") > 0)
            {
                newstr = "<span style='color:red'>" + newstr + "</span>";
            }
            if (old.IndexOf("<b>") > 0)
            {
                newstr = "<b>" + newstr + "</b>";
            }
            return newstr;
        }

        /// <summary>
        /// 返回包含中文字符的字符串长度
        /// C# 的string.Length中中文字只做1位统计,所以要将其转换为2位
        /// </summary>
        /// <param name="strSource">要统计长度的字符串变量</param>
        /// <returns>字符串长度</returns>
        public static int GetLength(string strSource)
        {
            return Encoding.GetEncoding("GB18030").GetBytes(strSource).Length;
        }

        /// <summary>
        /// 是否包含图片
        /// </summary>
        /// <param name="text">内容</param>
        /// <returns></returns>
        public static bool isHaveImg(String text)
        {
            if (text == null && text == "") return false;
            bool t = false;
            Regex regex = new Regex(@"src\s*=\s*(?:([""'])(?<src>[^""']+)\1|(?<src>[^\s>]+))", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            MatchCollection mc = regex.Matches(text);
            for (int i = 0; i < mc.Count; i++)
            {
                if (mc[i].Success)
                {
                    t = true;
                    break;
                }
                else
                {
                    t = false;
                }
            }
            if (t)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取图片的路径
        /// </summary>
        /// <param name="text">内容</param>
        /// <returns></returns>
        public static String getImgSrc(String text)
        {
            Regex regex = new Regex(@"src\s*=\s*(?:([""'])(?<src>[^""']+)\1|(?<src>[^\s>]+))", RegexOptions.IgnoreCase | RegexOptions.Singleline);
            MatchCollection mc = regex.Matches(text);

            for (int i = 0; i < mc.Count; i++)
            {
                if (mc[0].Success)
                {
                    text = mc[0].Groups["src"].Value;
                }
            }

            return text;
        }


        /// <summary>
        /// 得到字符的ascii码
        /// </summary>
        public static int ascii(string chr)
        {
            Encoding ecode = Encoding.GetEncoding("gb18030");
            byte[] codebytes = ecode.GetBytes(chr.ToString());
            if (isDouble(chr))
            {
                // 双字节码为高位乘256，再加低位
                // 该为无符号码，再减65536
                return (int)codebytes[0] * 256 + (int)codebytes[1] - 65536;
            }
            else
            {
                return (int)codebytes[0];
            }
        }

        /// <summary>
        /// 对字符串进行处理。
        /// </summary>
        public static String checkStr(String str)
        {
            if (string.IsNullOrEmpty(str)) str = "";

            str = str.Trim();
            str = Regex.Replace(str, "[\\s]{2,}", " ");
            str = str.Replace("'", "''");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace(";", "；");
            return str;
        }
        public static String dataStr(String str)
        {
            if (string.IsNullOrEmpty(str))
                return string.Empty;
            //str = str.Trim();
            str = str.Replace("<p>", "");
            str = str.Replace("</p>", "");
            str = str.Replace("&nbsp;", "");
            str = str.Replace("<P>", "");
            str = str.Replace("</P>", "");
            str = str.Replace("<br>", "");
            str = str.Replace("<br />", "");
            str = str.Replace("<strong>", "");
            str = str.Replace("</strong>", "");
            str = str.ToLower().Replace("exec", "e_xec");
            str = str.ToLower().Replace("declare", "d_eclare");
            return str;
        }



        public static string escape(string s)
        {
            ////在C#后台实现JavaScript的函数escape()的字符串转换
            StringBuilder sb = new StringBuilder();
            byte[] byteArr = System.Text.Encoding.Unicode.GetBytes(s);

            for (int i = 0; i < byteArr.Length; i += 2)
            {
                sb.Append("%u");
                sb.Append(byteArr[i + 1].ToString("X2"));//把字节转换为十六进制的字符串表现形式

                sb.Append(byteArr[i].ToString("X2"));
            }
            return sb.ToString();

        }



        public static string unescape(string s)
        {
            //把JavaScript的escape()转换过去的字符串解释回来
            string str = s.Remove(0, 2);//删除最前面两个＂%u＂
            string[] strArr = str.Split(new string[] { "%u" }, StringSplitOptions.None);//以子字符串＂%u＂分隔
            byte[] byteArr = new byte[strArr.Length * 2];
            for (int i = 0, j = 0; i < strArr.Length; i++, j += 2)
            {
                byteArr[j + 1] = Convert.ToByte(strArr[i].Substring(0, 2), 16);  //把十六进制形式的字串符串转换为二进制字节
                byteArr[j] = Convert.ToByte(strArr[i].Substring(2, 2), 16);
            }
            str = System.Text.Encoding.Unicode.GetString(byteArr);　//把字节转为unicode编码
            return str;

        }
        //默认密钥向量
        private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        /// <summary>
        /// DES加密字符串
        /// </summary>
        /// <param name="encryptString">待加密的字符串</param>
        /// <param name="encryptKey">加密密钥,要求为8位</param>
        /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
        public static string Encode(string encryptString, string encryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
                DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Convert.ToBase64String(mStream.ToArray());
            }
            catch
            {
                return encryptString;
            }
        }

        /// <summary>
        /// DES解密字符串
        /// </summary>
        /// <param name="decryptString">待解密的字符串</param>
        /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
        /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
        public static string Decode(string decryptString, string decryptKey)
        {
            try
            {
                byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
                byte[] rgbIV = Keys;
                byte[] inputByteArray = Convert.FromBase64String(decryptString);
                DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
                MemoryStream mStream = new MemoryStream();
                CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                cStream.Write(inputByteArray, 0, inputByteArray.Length);
                cStream.FlushFinalBlock();
                return Encoding.UTF8.GetString(mStream.ToArray());
            }
            catch
            {
                return decryptString;
            }
        }



        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="strHtml">包括HTML的源码 </param>
        /// <returns>已经去除后的文字</returns>
        public static string StripHTML(string strHtml)
        {
            string[] aryReg ={
          @"<script[^>]*?>.*?</script>",
          @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""@#])(\\[""@#tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
          @"([\r\n])[\s]+",
          @"&(quot|#34);",
          @"&(amp|#38);",
          @"&(lt|#60);",
          @"&(gt|#62);", 
          @"&(nbsp|#160);", 
          @"&(iexcl|#161);",
          @"&(cent|#162);",
          @"&(pound|#163);",
          @"&(copy|#169);",
          @"&#(\d+);",
          @"-->",
          @"<!--.*\n"
           };

            string[] aryRep = {
           "",
           "",
           "",
           "\"",
           "&",
           "<",
           ">",
           " ",
           "\xa1",//chr(161),
           "\xa2",//chr(162),
           "\xa3",//chr(163),
           "\xa9",//chr(169),
           "",
           "\r\n",
           ""
          };
            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }

            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace("\r\n", "");


            return strOutput;
        }


        public static string CleanAll(string strHtml)
        {
            if (string.IsNullOrEmpty(strHtml))
            {
                strHtml = " ";
            }
            string[] aryReg ={
          @"<script[^>]*?>.*?</script>",
          @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""@#])(\\[""@#tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
          @"([\r\n])[\s]+",
          @"&(quot|#34);",
          @"&(amp|#38);",
          @"&(lt|#60);",
          @"&(gt|#62);", 
          @"&(nbsp|#160);", 
          @"&(iexcl|#161);",
          @"&(cent|#162);",
          @"&(pound|#163);",
          @"&(copy|#169);",
          @"&#(\d+);",
          @"-->",
          @"<!--.*\n"
           };

            string[] aryRep = {
           "",
           "",
           "",
           "",
           "",
           "",
           "",
           "",
           "",//chr(161),
           "",//chr(162),
           "",//chr(163),
           "",//chr(169),
           "",
           "",
           ""
          };
            string newReg = aryReg[0];
            string strOutput = strHtml;
            for (int i = 0; i < aryReg.Length; i++)
            {
                Regex regex = new Regex(aryReg[i], RegexOptions.IgnoreCase);
                strOutput = regex.Replace(strOutput, aryRep[i]);
            }

            strOutput.Replace("<", "");
            strOutput.Replace(">", "");
            strOutput.Replace("\r\n", "");


            return strOutput;
        }


        /// <summary>
        /// 获取弹出提示框内容
        /// </summary>
        /// <param name="text">提示内容</param>
        /// <param name="what">回去方式，-1表示返回，其它表示回去的URL地址</param>
        /// <param name="p">当前页的page类</param>
        public static void Alert(string text, string where, Page p)
        {
            string Str = "";

            text = text.Trim();
            if (where == "-1")
            {
                Str = Str + "<script language=\"javascript\">alert(\"" + text + "\");history.go(-1)</script>";
            }
            else
            {
                Str += "<script language=\"javascript\">alert(\"" + text + "\");window.location=\"" + where + "\"</script>";
            }
            p.Response.Write(Str);
            p.Response.End();
        }
        /// <summary>
        /// 弹出提示框并终止执行下面的操作
        /// </summary>
        /// <param name="text">提示文字</param>
        /// <param name="what">跳转的路径如果是'-1'则调回原来的页面</param>
        public static void Alert(string text, string where)
        {
            string Str = "";

            text = text.Trim();
            if (where == "-1")
            {
                Str = Str + "<script language=\"javascript\">alert(\"" + text + "\");history.go(-1)</script>";
            }
            else
            {
                Str += "<script language=\"javascript\">alert(\"" + text + "\");window.location=\"" + where + "\"</script>";
            }
            System.Web.HttpContext.Current.Response.Write(Str);
            System.Web.HttpContext.Current.Response.End();

        }
        public static void Confirm(string text, string where)
        {
            string Str = "";

            text = text.Trim();
            Str = Str + "<script language=\"javascript\">if(confirm(\"" + text + "\")){window.location=\"" + where + "\"}else{history.go(-1)}</script>";
            System.Web.HttpContext.Current.Response.Write(Str);
            System.Web.HttpContext.Current.Response.End();

        }

        /// <summary>
        /// 填出提示信息，不跳转,endResponse=true则结束输出
        /// </summary>
        /// <param name="text"></param>
        /// <param name="endResponse"></param>
        public static void Alert(string text, bool endResponse)
        {
            string Str = "";

            text = text.Trim();

            Str = "<script language=\"javascript\">alert(\"" + text + "\");</script>";
            System.Web.HttpContext.Current.Response.Write(Str);
            if (endResponse)
                System.Web.HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {


            string result = "";
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result == null || result == "")
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (result == null || result == "")
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (result == null || result == "")
            {
                return "0.0.0.0";
            }

            return result;

        }

        /// <summary>
        /// 比较时间间隔
        /// </summary>
        /// <param name="DateTime1">时间一，当前时间</param>
        /// <param name="DateTime2">时间二，用于做对比的</param>
        /// <param name="mode">"d"天 "h"小时 "m" 分 "s"秒</param>
        /// <returns></returns>
        public static string DateDiff(DateTime DateTime1, DateTime DateTime2, string mode)
        {
            string dateDiff = null;
            TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
            TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            if (mode == "d")
            {
                dateDiff = ts.Days.ToString();
            }
            else if (mode == "h")
            {
                dateDiff = ts.Hours.ToString();
            }
            else if (mode == "m")
            {
                dateDiff = ts.Minutes.ToString();
            }
            else if (mode == "s")
            {
                dateDiff = ts.Seconds.ToString();
            }
            return dateDiff;
        }


        public static bool isRequestNull(string ssc, Page p)
        {
            bool isT = false;
            if (p.Request[ssc] == null || p.Request[ssc].ToString() == "")
            {
                isT = false;
            }
            else
            {
                isT = true;
            }
            return isT;
        }


        /// <summary>
        /// 处理textarea中数据进入数据库
        /// </summary>
        /// <param name="str">待处理的字符串</param>
        /// <returns></returns>
        public static string str_add(string str)
        {
            if (string.IsNullOrEmpty(str)) str = "";
            str = str.Replace(" ", "&nbsp;");
            str = str.Replace("'", "''");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("\n", "<br>");
            return str;
        }

        /// <summary>
        /// 从数据库提取数据到textarea中
        /// </summary>
        /// <param name="str">待处理的字符串</param>
        /// <returns></returns>
        public static string str_edit(string str)
        {
            if (string.IsNullOrEmpty(str)) str = "";
            str = str.Replace("&nbsp;", " ");
            str = str.Replace("''", "'");
            str = str.Replace("<br>", "\n");
            str = str.Replace("&lt;", "<");
            str = str.Replace("&gt;", ">");
            return str;
        }

        /// <summary>
        /// 验证邮箱合法性
        /// </summary>
        /// <param name="inputEmail"></param>
        /// <returns></returns>
        public static bool isEmail(string inputEmail)
        {
            string strRegex = @"^([a-zA-Z0-9_\-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9\-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$";
            Regex re = new Regex(strRegex);
            if (re.IsMatch(inputEmail))
                return (true);
            else
                return (false);
        }

        /// <summary>
        /// 验证是否为合法的用户名
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static bool IsValidUserName(string input)
        {
            return Regex.IsMatch(input, @"^\w+$");
        }

        /// <summary>
        /// Md5加密
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string Md5(string input)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(input, "MD5");
        }

        /// <summary>
        /// 过滤相同字符串
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string FilterSameString(string[] text)
        {
            string Result = "";
            List<string> listString = new List<string>();
            foreach (string eachString in text)
            {
                if (!listString.Contains(eachString))
                    listString.Add(eachString);
            }
            foreach (string eachString in listString)
            {
                Result += eachString + ",";
            }
            return Result.Substring(0, Result.Length - 1);
        }
        /// <summary>
        /// 生成上传文件时用到文件名用日期时间随机数生成
        /// </summary>
        /// <param name="ext">文件扩展名</param>
        /// <returns></returns>
        public static string GetFileName(string ext)
        {
            string fileName = "";
            Random rd = new Random();
            fileName += DateTime.Now.ToString("yyyyMMddhhmmssss") + rd.Next(1000, 10000).ToString() + "." + ext;
            return fileName;
        }

        /// <summary>
        /// 返回指定小数点位数的值
        /// </summary>
        /// <param name="text">值</param>
        /// <param name="i">位数</param>
        /// <returns></returns>
        public static decimal GetNum(decimal text, int i)
        {

            return Math.Round(text, i);

        }

        /// <summary>
        /// 判断是否存在cookie
        /// </summary>
        /// <param name="name">cookie名称</param>
        /// <param name="key">cookie值名称</param>
        /// <returns></returns>
        public static bool HaveCookie(string name, string key)
        {
            if (HttpContext.Current.Request.Cookies[name] != null && HttpContext.Current.Request.Cookies[name][key] != null && HttpContext.Current.Request.Cookies[name][key].ToString() != "")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 处理商品图片路径
        /// </summary>
        /// <param name="path">原始路径数据</param>
        /// <returns></returns>
        public static string[] SolvePicPath(string path)
        {
            List<string> pathlist = new List<string>();
            if (string.IsNullOrEmpty(path))
            {
                pathlist.Add("/images/nopublic.jpg");
            }
            else
            {
                string[] a = path.Split(new[] { '|' });
                foreach (string p in a)
                {
                    if (p.IndexOf(',') > -1)
                    {
                        pathlist.Add("/upfile/" + p.Split(new[] { ',' })[1]);
                    }
                }
            }
            return pathlist.ToArray();
        }
        /// <summary>
        /// 获取商品图片路径
        /// </summary>
        /// <param name="path"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static string GetPicPath(string path, int index)
        {
            string newpath = "/images/nopublic.jpg";

            if (!string.IsNullOrEmpty(path))
            {
                string[] a = path.Split(new[] { '|' });

                if (a.Length >= index + 1)
                {
                    List<string> pathlist = new List<string>();
                    foreach (string p in a)
                    {
                        if (p.IndexOf(',') > -1)
                        {
                            pathlist.Add("/upfile/" + p.Split(new[] { ',' })[1]);
                        }
                    }
                    if (pathlist.Count >= index + 1)
                    {
                        newpath = pathlist[index];
                    }
                }
            }
            return newpath;
        }
        /// <summary>
        /// 返回数组里的最大值或最小值
        /// </summary>
        /// <param name="arr">数组</param>
        /// <param name="k">max or min</param>
        /// <returns></returns>
        public static decimal sValue(decimal[] arr, string k)
        {

            int sort = 0;
            ArrayList list = new ArrayList(arr);
            list.Sort();
            if (k == "max")
            {
                sort = Convert.ToInt32(list[list.Count - 1]);
            }
            else if (k == "min")
            {
                sort = Convert.ToInt32(list[0]);
            }

            return sort;
        }

        /// <summary>
        /// 将指定如"1,23|2,13|3,45"转化为int {23,13,45}
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static decimal[] IntArr(string[] str)
        {
            string q = "";
            for (int i = 0; i < str.Length; i++)
            {

                q += str[i].Split(',')[1] + ",";
            }
            q = q.Substring(0, q.Length - 1);
            string[] old = q.Split(',');
            decimal[] newInt = new decimal[old.Length];
            for (int j = 0; j < old.Length; j++)
            {
                newInt[j] = decimal.Parse(old[j]);
            }

            return newInt;
        }
        /// <summary>
        /// 返回用&lt;script type="text/javascript"&gt;&lt;/script&gt;包裹的字符串
        /// </summary>
        /// <param name="script">javascript内容，如alert("ok")</param>
        /// <returns></returns>
        public static string GetClientScript(string script)
        {
            return string.Format("<script type=\"text/javascript\">{0}</script>", script);
        }
        /// <summary>
        /// 16位MD5加密
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <returns></returns>
        public static string GetMd5Str(string ConvertString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
            t2 = t2.Replace("-", "");
            return t2;
        }
        /// <summary>
        /// 去除标红和加粗
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetNoHtml(string str)
        {
            return str.Replace("<span style='color:red'>", "").Replace("</span>", "").Replace("<b>", "").Replace("</b>", "");
        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="strSmtpServer"></param>
        /// <param name="strFrom">发件人地址</param>
        /// <param name="strFromPass">发件人密码</param>
        /// <param name="strto">收件人</param>
        /// <param name="strSubject">主题</param>
        /// <param name="strBody">内容</param>
        public static void SendSMTPEMail(string strSmtpServer, string strFrom, string strFromPass, string strto, string strSubject, string strBody)
        {
            System.Net.Mail.SmtpClient client = new SmtpClient(strSmtpServer);
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential(strFrom, strFromPass);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            System.Net.Mail.MailMessage message = new MailMessage(strFrom, strto, strSubject, strBody);
            message.BodyEncoding = System.Text.Encoding.UTF8;
            message.IsBodyHtml = true;
            client.Send(message);
        }
        /// <summary>
        /// 返回数字 格式类似(1,000,000)
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetMoneyFormat(object obj)
        {
            string dou = Convert.ToString(obj);
            if (dou.LastIndexOf('.') > 0)
            {
                dou = dou.Substring(0, dou.LastIndexOf('.'));
            }
            int mon = Convert.ToInt32(dou);
            string num = "";
            string temp = mon.ToString();
            if (mon > 999)
            {

                for (int i = temp.Length; i > 3; i -= 3)
                {
                    num += "," + temp.Substring(temp.Length - 3, 3);
                    temp = temp.Substring(0, temp.Length - 3);
                }
                string hnum = mon.ToString().Substring(0, (mon.ToString().Length) % 3);
                temp = hnum + temp;
            }
            else
            {
                num = temp;
            }
            return num;
        }
        /// <summary>
        /// 根据bool返回自定义的string
        /// </summary>
        /// <param name="key">bool(object)</param>
        /// <param name="TrueString">True:Result</param>
        /// <param name="FlaseString">Flase:Result</param>
        /// <returns></returns>
        public static string GetBoolToString(object key, string TrueString, string FlaseString)
        {
            if (GetBool(key))
            {
                return TrueString;
            }
            else
            {
                return FlaseString;
            }
        }
        /// <summary>
        /// 根据值快速返回bool,如转换1或true
        /// </summary>
        /// <param name="key">string values</param>
        /// <returns>bool</returns>
        public static bool GetBool(object key)
        {
            try
            {
                if (key.ToString() == "1" || key.ToString().ToUpper() == "TRUE")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch { return false; }
        }
        public static string GetDayOfWeek(object obj)
        {
            int day = Convert.ToInt32(obj);
            if (day == 1)
            {
                return "星期一";
            }
            else if (day == 2)
            {
                return "星期二";
            }
            else if (day == 3)
            {
                return "星期三";
            }
            else if (day == 4)
            {
                return "星期四";
            }
            else if (day == 5)
            {
                return "星期五";
            }
            else if (day == 6)
            {
                return "星期六";
            }
            else
            {
                return "星期日";
            }
        }
        /// <summary>
        /// 根据时间判断是上午还是下午
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetAMPM(object obj)
        {
            int hour = Convert.ToInt32(obj);
            if (hour >= 0 && hour < 12)
            {
                return "上午好";
            }
            else if (hour >= 12 && hour < 18)
            {
                return "下午好";
            }
            else
            {
                return "晚上好";
            }
        }
        /// <summary>
        /// 得到服务器上文件的绝对路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string ServerPath(string path)
        {
            return System.Web.HttpContext.Current.Server.MapPath(path);
        }
        public static string GetFlowerTypeName(string key)
        {
            switch (key)
            {
                case "1":
                    return "tj";
                case "开业花篮":
                    return "ky";
                case "生日鲜花":
                    return "sr";
                case "爱情鲜花":
                    return "tm";
                case "祝福鲜花":
                    return "zf";
                default:
                    return "index";
            }
        }

    }
}
